<template>
  <view v-if="aiStore.showDialog" class="ai-dialog-mask">
    <view class="ai-chat-container">
      <!-- 顶部标题栏 -->
      <view class="chat-header">
        <view class="header-left">
          <image src="/static/icon/AI/ai.png" mode="aspectFit" class="header-avatar" />
          <text class="header-title">AI智能客服</text>
        </view>
        <button class="close-btn" @click="aiStore.toggleDialog(false)">
          <image src="/static/icon/AI/close.png" mode="aspectFit" class="close-icon" />
        </button>
      </view>

      <!-- 聊天内容区域 -->
      <scroll-view
          scroll-y
          class="chat-history"
          :scroll-into-view="scrollIntoView"
          :scroll-with-animation="true"
      >
        <!-- AI消息（左侧：头像 + 对话框） -->
        <view
            v-for="(msg, idx) in aiStore.messages"
            :key="idx"
            :id="'msg-' + idx"
            class="message-row"
            :class="msg.role === 'user' ? 'user-row' : 'ai-row'"
        >
          <!-- AI消息 -->
          <template v-if="msg.role === 'ai'">
            <image
                src="/static/icon/AI/ai.png"
                mode="aspectFit"
                class="avatar ai-avatar"
            />
            <view class="message-bubble ai-bubble">
              <view class="message-content" v-html="msg.content"></view>
              <view class="message-time">{{ formatTime(msg.timestamp) }}</view>
            </view>
            <view class="empty-space"></view> <!-- 右侧占位，保持对齐 -->
          </template>

          <!-- 用户消息 -->
          <template v-if="msg.role === 'user'">
            <view class="empty-space"></view> <!-- 左侧占位，保持对齐 -->
            <view class="message-bubble user-bubble">
              <view class="message-content" v-html="msg.content"></view>
              <view class="message-time">{{ formatTime(msg.timestamp) }}</view>
            </view>
            <image
                :src="userInfo.avatar"
                mode="aspectFit"
                class="avatar user-avatar"
            />
          </template>
        </view>
      </scroll-view>

      <!-- 底部输入区域 -->
      <view class="input-area">
        <view class="input-bar">
          <button class="upload-btn" @click="handleUpload">
            <image src="/static/icon/AI/photo.png" mode="aspectFit" class="upload-icon" />
          </button>

          <input
              v-model="userInput"
              class="chat-input"
              placeholder="请输入你的问题..."
              :disabled="loading"
              @confirm="onSend"
              confirm-type="send"
          />

          <button
              class="send-btn"
              @click="onSend"
              :disabled="loading || !userInput"
              :class="{ disabled: loading || !userInput }"
          >
            <text v-if="!loading">发送</text>
            <view v-else class="loading-indicator">
              <view class="loading-dot"></view>
              <view class="loading-dot"></view>
              <view class="loading-dot"></view>
            </view>
          </button>
        </view>

        <view class="status-area">
          <view v-if="loading" class="loading-hint">
            <text>AI思考中...</text>
          </view>
          <view v-if="errorMsg" class="error-message">
            <text>{{ errorMsg }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useAiServerChatStore } from '@/store/aiServerChatStore'

// 类型定义（修复Message类型引用问题）
interface Message {
  role: 'user' | 'ai';
  content: string;
  timestamp: number;
}

const aiStore = useAiServerChatStore()
const userInfo=uni.getStorageSync('userInfo')
// 本地状态
const userInput = ref('')
const loading = ref(false)
const errorMsg = ref('')
const scrollIntoView = ref('')
const messageId = ref('')
const request = ref({
  sessionId: aiStore.sessionId,
  messageId: '',
  userId: userInfo.userId,
  userInput: '',
  aiResponse: ''
})
const filePath = ref('')

// 组件挂载时记录状态
onMounted(() => {
  console.log('AI聊天组件挂载，当前对话框状态:', aiStore.showDialog)
})

// 初始化会话ID
onMounted(() => {
  if (!aiStore.sessionId) {
    const timestamp = Date.now().toString(36)
    const randomStr = Math.random().toString(36).substr(2, 9)
    aiStore.setSessionId("mini" + timestamp + randomStr)
  }
  request.value.sessionId = aiStore.sessionId
})

// 发送消息
const onSend = async () => {
  if (!userInput.value.trim() || loading.value) return

  let input = userInput.value.trim();
  const hasImage = !!filePath.value// 判断是否有图片路径
  // 拼接规则：文字 + 图片路径（根据需求自定义格式，此处用换行分隔）
  if (hasImage) {
    input =  `${input}\n[图片filePath]${filePath.value}`
  }
  // 添加用户消息
  const userMessage: Message = {
    role: 'user',
    content: input,
    timestamp: Date.now()
  }
  aiStore.addMessage(userMessage)

  userInput.value = ''
  filePath.value = ''
  loading.value = true
  errorMsg.value = ''

  await nextTick()
  scrollToBottom()

  // 添加AI消息占位
  const aiMessage: Message = {
    role: 'ai',
    content: '',
    timestamp: Date.now()
  }
  aiStore.addMessage(aiMessage)
  await nextTick()
  scrollToBottom()

  // 流式请求（假设存在saveMessage方法）
  await streamAIResponse(input, aiMessage)
}

// 流式获取AI回复
function streamAIResponse(input: string, aiMessage: Message) {
  let finished = false
  let lastLength = 0
  request.value.userInput = input

  const poll = async () => {
    if (finished) return
    try {
      await new Promise<void>((resolve) => {
        uni.request({
          url: 'http://localhost:1010/ai/aiServerChat/stream',
          method: 'POST',
          data: request.value,
          header: { Accept: 'text/event-stream' },
          timeout: 60000,
          success: (res) => {
            const raw = res.data as string
            const lines = raw.split(/\r?\n/).filter(l => l.startsWith('data:'))
            let newText = ''

            for (let i = lastLength; i < lines.length; i++) {
              const chunk = lines[i].replace(/^data:/, '').trim()
              if (chunk === '[END]') {
                finished = true
                break
              }
              newText += chunk
            }

            if (newText) {
              aiMessage.content += newText
              // 更新最后一条消息（AI回复）
              const messages = [...aiStore.messages]
              messages[messages.length - 1] = aiMessage
              aiStore.saveMessages(messages)

              lastLength = lines.length
              nextTick(scrollToBottom)
            }

            if (finished || !newText) {
              finished = true
              loading.value = false
              saveChatRecord(input, aiMessage.content)
              resolve()
            } else {d
              setTimeout(poll, 600)
              resolve()
            }
          },
          fail: () => {
            errorMsg.value = 'AI请求失败'
            loading.value = false
            finished = true
            resolve()
          }
        })
      })
    } catch {
      loading.value = false
      finished = true
    }
  }
  poll()
}

// 保存对话记录（假设存在saveMessage方法）
function saveChatRecord(user: string, ai: string) {
  const timestamp = Date.now().toString(36)
  const randomStr = Math.random().toString(36).substr(2, 9)
  messageId.value = "mini" + timestamp + randomStr

  request.value.messageId = messageId.value
  request.value.userInput = user
  request.value.aiResponse = ai

  // saveMessage(request.value)
}

// 上传文件
const handleUpload = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths
      if (!tempFilePaths.length) {
        errorMsg.value = '未选择文件'
        return
      }

      uni.uploadFile({
        url: 'http://localhost:10000/oss/upload',
        filePath: tempFilePaths[0],
        name: 'file',
        success: (uploadRes) => {
          try {
            const result = JSON.parse(uploadRes.data)
            if (result.code === 200) {
              const imageUrl = result.data.url
              filePath.value = imageUrl

              // 直接添加图片消息
              const imageMessage: Message = {
                role: 'user',
                content: `<img src="${imageUrl}" style="max-width: 100%; border-radius: 8rpx;" />`,
                timestamp: Date.now()
              }
              aiStore.addMessage(imageMessage)

              nextTick(scrollToBottom)
            } else {
              errorMsg.value = `服务器错误: ${result.msg || uploadRes.statusCode}`
            }
          } catch (e) {
            errorMsg.value = '解析响应失败'
          }
        },
        fail: (err) => {
          errorMsg.value = `上传失败: ${err.errMsg}`
        }
      })
    },
    fail: (err) => {
      errorMsg.value = `选择图片失败: ${err.errMsg}`
    }
  })
}

// 滚动到底部
function scrollToBottom() {
  scrollIntoView.value = 'msg-' + (aiStore.messages.length - 1)
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}
</script>

<style lang="scss" scoped>
/* 遮罩层 */
.ai-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}

/* 聊天容器 - 确保完整显示 */
.ai-chat-container {
  width: 100%;
  max-width: 750rpx; /* 限制最大宽度，避免过宽 */
  height: 85vh; /* 调整高度，避免超出屏幕 */
  background-color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 50rpx rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.chat-header {
  padding: 24rpx 30rpx;
  background: linear-gradient(135deg, #1e88e5, #1565c0);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
  }

  .header-avatar {
    width: 56rpx;
    height: 56rpx;
    border-radius: 50%;
    margin-right: 16rpx;
    background-color: white;
    padding: 4rpx;
  }

  .header-title {
    font-size: 28rpx;
    font-weight: 500;
  }

  .close-btn {
    width: 52rpx;
    height: 52rpx;
    padding: 0;
    border-radius: 50%;
    margin-left: 360rpx; /* 仅保留少量左 margin */
    display: flex;
    justify-content: center;
    align-items: center;
  }

}

/* 聊天历史区域 - 确保内容完整显示 */
.chat-history {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  background-color: #f7f9fc;
  box-sizing: border-box; /* 确保内边距不影响整体尺寸 */
}

/* 消息行 - 核心布局 */
.message-row {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  margin-bottom: 30rpx;
  width: 100%; /* 占满宽度，确保左右布局 */
  box-sizing: border-box;
  padding: 0 10rpx; /* 增加左右内边距，避免边缘紧贴 */
}

/* AI消息行 - 左侧布局 */
.ai-row {
  justify-content: flex-start; /* 左对齐 */
}

/* 用户消息行 - 右侧布局 */
.user-row {
  justify-content: flex-end; /* 右对齐 */
}

/* 头像样式 */
.avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  flex-shrink: 0; /* 不压缩头像尺寸 */
  margin-top: 5rpx; /* 轻微下移，与对话框对齐 */
}

/* AI头像 - 左侧 */
.ai-avatar {
  margin-right: 16rpx; /* 与对话框保持距离 */
}

/* 用户头像 - 右侧 */
.user-avatar {
  margin-left: 16rpx; /* 与对话框保持距离 */
}

/* 消息气泡 - 核心样式 */
.message-bubble {
  max-width: 70%; /* 限制最大宽度，避免过宽 */
  border-radius: 20rpx;
  padding: 20rpx 24rpx;
  position: relative;
  word-break: break-word;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}

/* AI气泡 - 左侧 */
.ai-bubble {
  background-color: white;
  border: 1rpx solid #f0f0f0;
  margin-right: auto; /* 左侧气泡自动靠左 */
}

/* 用户气泡 - 右侧 */
.user-bubble {
  background: linear-gradient(135deg, #1e88e5, #42a5f5);
  color: white;
  margin-left: auto; /* 右侧气泡自动靠右 */
}

/* 气泡内容 */
.message-content {
  font-size: 28rpx;
  line-height: 1.6;
  margin-bottom: 8rpx; /* 与时间保持距离 */
}

/* 时间显示 */
.message-time {
  font-size: 20rpx;
  text-align: right;
  opacity: 0.7;
}

/* 空白占位 - 确保左右布局对齐 */
.empty-space {
  width: 64rpx; /* 与头像宽度一致，保持布局平衡 */
  flex-shrink: 0;
}

/* 输入区域 */
.input-area {
  padding: 20rpx;
  background-color: white;
  border-top: 1rpx solid #f0f0f0;
}

.input-bar {
  display: flex;
  align-items: center;
  background-color: #f7f8fa;
  border-radius: 40rpx;
  padding: 8rpx 16rpx;
}

.upload-btn {
  width: 68rpx;
  height: 68rpx;
  padding: 0;
  background-color: transparent;
  border: none;
}

.upload-icon {
  width: 36rpx;
  height: 36rpx;
  opacity: 0.7;
}

.chat-input {
  flex: 1;
  height: 68rpx;
  padding: 0 16rpx;
  background-color: transparent;
  font-size: 28rpx;
  color: #333;
  border: none;
}

.send-btn {
  width: 100rpx;
  height: 68rpx;
  margin-left: 10rpx;
  background: linear-gradient(135deg, #1e88e5, #1565c0);
  color: white;
  border-radius: 34rpx;
  font-size: 28rpx;
  padding: 0;
  border: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

.send-btn.disabled {
  background-color: #cccccc;
  opacity: 0.7;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-dot {
  width: 10rpx;
  height: 10rpx;
  background-color: white;
  border-radius: 50%;
  margin: 0 3rpx;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) { animation-delay: -0.32s; }
.loading-dot:nth-child(2) { animation-delay: -0.16s; }

.status-area {
  margin-top: 16rpx;
  min-height: 40rpx;
  text-align: center;
}

.loading-hint {
  color: #999;
  font-size: 24rpx;
}

.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
}

/* 动画 */
@keyframes loading {
  0%, 80%, 100% { transform: scale(0.4); }
  40% { transform: scale(1); }
}
</style>